<template>
  <div class="app-container">
    <el-form :inline="true" :model="listQuery" @submit.native.prevent>
      <el-form-item label="商家名称">
        <el-input size="small" v-model="listQuery.q_company"></el-input>
      </el-form-item>
      <!-- <el-form-item label="用户名">
        <el-input size="small" v-model="listQuery.q_name"></el-input>
      </el-form-item>
      <el-form-item label="状态">
        <el-select
          class="toolbar-lable-right"
          size="small"
          v-model="listQuery.q_state"
          placeholder="请选择"
        >
          <el-option
            v-for="item in optStateValues"
            :key="item.value"
            :label="item.name"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="small" @click="this.getList">查询</el-button>
        <el-button icon="el-icon-refresh" size="small" @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- <div class="button-table-margin">
      <el-button size="small" type="primary" @click="viewDetails">详情</el-button>
      <el-button size="small" type="primary" @click="append">添加</el-button>
      <el-button size="small" type="primary" @click="edit">修改</el-button>
      <el-button size="small" type="primary" @click="passBtn">审核通过</el-button>
      <el-button size="small" type="primary" @click="rejectBtn">审核驳回</el-button>
      <el-button size="small" type="primary" @click="deleteBtn">删除</el-button>
    </div> -->
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane :label="`待审核(${auditCount})`"  name="first"></el-tab-pane>
      <el-tab-pane :label="`审核拒绝(${rejectCount})`" name="second"></el-tab-pane>
    </el-tabs>
    <el-table
      ref="singleTable"
      :data="dataList"
      v-loading="listLoading"
      border
      fit
      highlight-current-row
      tooltip-effect="dark"
      style="width: 100%"
    >
      <el-table-column type="index" align="center" width="50">
      </el-table-column>
      <el-table-column show-overflow-tooltip property="name" label="用户名">
      </el-table-column>
      <el-table-column show-overflow-tooltip width="160" property="company" label="商家名称">
      </el-table-column>
      <el-table-column label="审核状态">
        <template slot-scope="scope">
          {{ codeBox.SELLER_APPLY_STATE[scope.row.state] }}
        </template>
      </el-table-column>
      <el-table-column width="200" property="bussinessLicense" label="营业执照编号">
      </el-table-column>
      <el-table-column width="200" property="taxLicense" label="统一社会信用代码">
      </el-table-column>
      <el-table-column width="160" property="telephone" label="联系电话">
      </el-table-column>
      <el-table-column show-overflow-tooltip width="200" property="companyAdd" label="地址">
      </el-table-column>
      <!-- <el-table-column width="200" property="organization" label="组织机构代码">
      </el-table-column> -->
      <el-table-column property="legalPerson" label="法人"> </el-table-column>
      <el-table-column width="160" property="personPhone" label="法人电话">
      </el-table-column>
      <el-table-column width="160" property="companyStartTime" label="营业开始时间"> </el-table-column>
      <el-table-column width="160" property="companyEndTime" label="营业结束时间"> </el-table-column>

      <el-table-column width="160" property="createTime" label="创建时间">
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="viewDetails(scope.row)"
          >详情</el-button>
          <el-button
            v-if="scope.row.state == 1"
            size="mini"
            type="text"
            icon="el-icon-check"
            @click="auditBtn(scope.row)"
          >审核</el-button>
          <el-button
            v-if="scope.row.state == 1"
            size="mini"
            type="text"
            icon="el-icon-edit"
           @click="edit(scope.row)"
          >编辑</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="deleteBtn(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />

    <el-dialog
      title="审核商家"
      :visible.sync="dialogVisible"
      width="30%"
    >
      <div class="dialog-row">
        <span class="label">商家名称：</span>
        <span class="value">{{ sellerName }}</span>
      </div>
      <div class="dialog-row">
        <span class="label">审核结果：</span>
        <el-radio-group v-model="auditResult">
          <el-radio :label="1">通过</el-radio>
          <el-radio :label="2">拒绝</el-radio>
        </el-radio-group>
      </div>
      <!-- 原因输入框（拒绝时必填） -->
      <div class="dialog-row" v-if="auditResult === 2">
        <span class="label">拒绝原因：</span>
        <el-input
          type="textarea"
          v-model="rejectReason"
          placeholder="请输入拒绝原因"
          :rows="3"
          resize="none"
        ></el-input>
      </div>
 
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitAudit">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>
<script>
import { getCodeManager, codeToArray } from "@/api/all";
import { applyListSearchSeller, passApplySeller, rejectApplySeller, deleteApplySeller, queryApplyCount } from "@/api/seller";
import Pagination from "@/components/Pagination";
import { Message } from "element-ui";
export default {
  name: 'sellerApply',
  components: { Pagination },
  data() {
    return {
      auditCount: 0,
      rejectCount: 0,
      activeName: "first",
      dialogVisible: false,
      sellerName: '', // 商家名称
      auditResult: 1, // 审核结果：1-通过，2-拒绝
      rejectReason: '', // 拒绝原因
      dataList: [],
      optStateValues: [],
      total: 0,
      listLoading: false,
      listQuery: {
        page: 1,
        limit: 20,
        q_company: "",
        q_state: "1",
        q_name: ""
      },
      currentRow: null,
    }
  },
  created() {
    // 状态
    getCodeManager("SELLER_APPLY_STATE", () => {
      this.optStateValues = codeToArray("SELLER_APPLY_STATE");
    });
    // 列表状态
    getCodeManager("SELLER_APPLY_STATE", () => {});
    this.getList();
    this.querySellerApplyCount();
  },
  methods: {
    handleClick(tab) {
      console.log(tab);
      if (tab.name === 'first') {
        this.listQuery.q_state = 1;
      } else if (tab.name === 'second') {
        this.listQuery.q_state = 4;
      }
      this.querySellerApplyCount();
      this.getList();
    },
    querySellerApplyCount(){
      const countQuery = {
        "q_name" : this.listQuery.q_name,
      }
      queryApplyCount(countQuery).then((res) => {
        console.log(res);
        if (res.data.data) {
          this.auditCount = res.data.data.auditCount;
          this.rejectCount = res.data.data.rejectCount;
        }
      });
    },
    getList() {
      this.listLoading = true;
      applyListSearchSeller(this.listQuery).then(res => {
        this.dataList = res.data.rows;
        this.total = res.data.total;
        this.listLoading = false;
      })
    },
    // handleCurrentChange(val) {
    //   // 选中当前行数据
    //   this.currentRow = val;
    // },
    viewDetails(row) {
      this.currentRow = row;
      // 查看详情
      if (!this.currentRow) {
        Message.error("请选择数据");
        return;
      }
      this.$router.push({ path: '/seller/sellerapplyaudit', query:{id: this.currentRow.id} })
    },
    append() {
      this.$router.push({ path: '/seller/sellerapplyadd' })
    },
    edit(row) {
      this.currentRow = row;
      if (!this.currentRow) {
        Message.error("请选择数据");
        return;
      }
      if (this.currentRow.state != 1 && this.currentRow.state != 4) {
        Message.error("只能修改提交申请和审核失败状态的商家申请");
        return;
      }
      this.$router.push({ path: '/seller/sellerapplyedit', query: { id: this.currentRow.id } })
    },
    auditBtn(row){
      this.currentRow = row;
      this.sellerName = row.company; // 从行数据获取商家名称
      this.auditResult = 1; // 默认选中“通过”
      this.rejectReason = ''; // 清空拒绝原因
      this.dialogVisible = true;
    },
    // 提交审核
    submitAudit() {
      if (this.auditResult === 2 && !this.rejectReason.trim()) {
        this.$message.warning('请填写拒绝原因');
        return;
      } 
      if(this.auditResult === 1) {
        passApplySeller({id: this.currentRow.id}).then(res => {
          if(res.data.success) {
            this.$message({
              type: 'success',
              message: '操作成功!'
            });
            this.getList()
          } else {
            this.$message({
              type: 'error',
              message: res.data.message
            });
          }
        })
      } else {
        rejectApplySeller({id: this.currentRow.id}).then(res => {
          if(res.data.success) {
            this.$message({
              type: 'success',
              message: '操作成功!'
            });
            this.getList()
          } else {
            this.$message({
              type: 'error',
              message: res.data.message
            });
          }
        })
      }
      this.dialogVisible = false;
      this.querySellerApplyCount();
      this.getList();
      },
    passBtn(row) {
      this.currentRow = row;
      // 审核通过
      if (!this.currentRow) {
        Message.error("请选择数据");
        return;
      }
      if (this.currentRow.state != 1 && this.currentRow.state != 4) {
        Message.error("只有提交审核才能进行此操作");
        return;
      }
      this.$confirm('确定要审核通过吗？', '提示', {
        onfirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        passApplySeller({id: this.currentRow.id}).then(res => {
          if(res.data.success) {
            this.$message({
              type: 'success',
              message: '操作成功!'
            });
            this.getList()
          } else {
            this.$message({
              type: 'error',
              message: res.data.message
            });
          }
        })
      }).catch(() => {
        this.$message({
            type: 'info',
            message: '取消审核'
          });
      })
    },
    rejectBtn(row) {
      this.currentRow = row;
      // 审核驳回
      if (!this.currentRow) {
        Message.error("请选择数据");
        return;
      }
      if (this.currentRow.state != 1 && this.currentRow.state != 4) {
        Message.error("只有提交审核才能进行此操作");
        return;
      }
      this.$confirm('确定要审核驳回吗？', '提示', {
        onfirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        rejectApplySeller({id: this.currentRow.id}).then(res => {
          if(res.data.success) {
            this.$message({
              type: 'success',
              message: '操作成功!'
            });
            this.getList()
          } else {
            this.$message({
              type: 'error',
              message: res.data.message
            });
          }
        })
      }).catch(() => {
        this.$message({
            type: 'info',
            message: '取消审核'
          });
      })
    },
    deleteBtn(row) {
      this.currentRow = row;
      // 删除
      if (!this.currentRow) {
        Message.error("请选择数据");
        return;
      }
      if (this.currentRow.state != 1 && this.currentRow.state != 4) {
        Message.error("只有提交审核和审核失败才能进行操作");
        return;
      }
      this.$confirm('确定要删除吗，删除后，该商家账号也会被删除，此操作不可撤销？', '提示', {
        onfirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteApplySeller({id: this.currentRow.id, userId: this.currentRow.userId}).then(res => {
          if(res.data.success) {
            this.$message({
              type: 'success',
              message: '操作成功!'
            });
            this.getList()
          } else {
            this.$message({
              type: 'error',
              message: res.data.message
            });
          }
        })
      }).catch(() => {
        this.$message({
            type: 'info',
            message: '取消删除'
          });
      })
    },
    reset() {
      this.listQuery.q_company = "";
      // this.listQuery.q_state = "";
      this.listQuery.q_name = "";
      this.getList();
    },
  }
}
</script>
